package com.yap.mvc;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import mvc.Users;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;

/**
 *
 * @author tadiwa
 */
@ManagedBean
@RequestScoped
public class PasswordChangeBean {

    private String password1;
    private String password2;
    @EJB
    private com.mvc.UsersFacade ejbFacade;

    public String getPassword1() {
        return password1;
    }

    public String getPassword2() {
        return password2;
    }

    public void setPassword1(String password1) {
        this.password1 = password1;
    }

    public void setPassword2(String password2) {
        this.password2 = password2;
    }

    public String changePassword() {
        String returnStatus = "failed";
        try {
            Subject subject = SecurityUtils.getSubject();
            String username = subject.getPrincipal().toString();

            if ((password1.length() < 6) || (password2.length() < 6)) {
                facesError("Password too short: At least 6 characters required.");
            } else if (password1.equals(password2)) {
                //proceed to login
                Users user = ejbFacade.getUserByUsername(username);
                user.setStatus("ACTIVE");

                //do login
                //  String oldPassword = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("oldPassword");
                // UsernamePasswordToken token = new UsernamePasswordToken(username, oldPassword);
                // FacesContext.getCurrentInstance().getExternalContext().getSessionMap().remove("oldPassword");
                //Perform Login
                // subject.login(token);
                //Change Password
                user.setPassword(new Sha256Hash(password1).toHex());
                ejbFacade.edit(user);
                // Redirect
                if (subject.hasRole("admin")) {
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/yapp/faces/index.xhtml");
                } else if (subject.hasRole("user")) {
                    FacesContext.getCurrentInstance().getExternalContext().redirect("/yapp/faces/index.xhtml");
                }
                return "success";
            } else {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Password Mismatch", null));
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return returnStatus;

    }

    private void facesError(String message) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, message, null));
    }
}
